// Copyright (C) joyinter
// All rights reserved.
// 
// Author : Jiang Li
// Date   : 2004-12-30

#include "stdafx.h"
#include "async_updateroom.h"
#include <common/svr_base/db_utility.h>
#include "msvr_server.h"
#include "msvr_room.h"

namespace JoyServer
{

static const int JOY_UPDATE_ROOM_MAX = 64;

// class CJoyAsyncUpdateRoom

void CJoyAsyncUpdateRoom::OnExecute()
{
    CArray<CRoomInfo>   roomInfos;
    // collect room informations.
    {
        CJoyAutoCS gate(m_server->m_userSetsLock);
        CJoyMainServer::CRoomMap& rooms = m_server->m_rooms;
        POSITION pos = rooms.GetStartPosition();
        while(pos != NULL)
        {
            CJoyMainRoom* pRoom;
            UINT roomId;
            rooms.GetNextAssoc(pos, roomId, pRoom);

            if(pRoom->m_closing)
            {
                continue;
            }

            CRoomInfo info;
            info.m_roomId   = pRoom->m_roomId;
            info.m_userNow  = pRoom->m_userNow;

            roomInfos.Add(info);
        }
    }

    // open session from online server data source.
    CJoyDbSession sessOServ;
    if(!JoyOpenDbSession(m_server, sessOServ,
        m_server->m_dbSetOServ.GetSource(m_server->m_serverId)))
    {
        return;
    }

    for(int i = 0; i < (int)roomInfos.GetCount(); i += JOY_UPDATE_ROOM_MAX)
    {
        int c = (int)roomInfos.GetCount()-i;
        if(c > JOY_UPDATE_ROOM_MAX)
        {
            c = JOY_UPDATE_ROOM_MAX;
        }
        CJoyDbBinary infos(&roomInfos[i], c);
        CJoyDbCommand updateCmd;
        JoyInvokeCommand(m_server, sessOServ, updateCmd,
            L"battle_update_room",
            infos,
            c);
    }
}


} // namespace JoyServer